﻿// ===============================================================================
// XCI.NET 西安交通信息WinForm开发框架 2018 版权所有
// ===============================================================================
using System;
using System.Collections.Generic;

namespace XCI.Helper
{
    /// <summary>
    /// Timer操作类
    /// </summary>
    public static class TimerHelper
    {
        private static readonly Dictionary<string, System.Timers.Timer> timers = new Dictionary<string, System.Timers.Timer>();

        /// <summary>
        /// 延迟执行
        /// </summary>
        /// <param name="delayTime">延迟时间,毫秒</param>
        /// <param name="execute">执行函数</param>
        public static void DelayExecuteWin(int delayTime, Action execute)
        {
            var time = new System.Windows.Forms.Timer();
            time.Interval = delayTime;
            time.Tick += (s, e) =>
            {
                time.Enabled = false;
                execute?.Invoke();
                time.Dispose();
            };
            time.Enabled = true;
        }

        /// <summary>
        /// 延迟执行
        /// </summary>
        /// <param name="delayTime">延迟时间,毫秒</param>
        /// <param name="execute">执行函数</param>
        public static void DelayExecute(int delayTime, Action execute)
        {
            var time = new System.Timers.Timer();
            time.Interval = delayTime;
            time.Elapsed += (s, e) =>
            {
                time.Enabled = false;
                execute?.Invoke();
                time.Dispose();
            };
            time.Enabled = true;
        }

        /// <summary>
        /// 定时执行
        /// </summary>
        /// <param name="name">任务名称</param>
        /// <param name="interval">时间间隔</param>
        /// <param name="execute">执行函数</param>
        public static void TimerExecute(string name, double interval, Action execute)
        {
            if (timers.ContainsKey(name)) return;
            var time = new System.Timers.Timer { Interval = interval };
            time.Elapsed += (s, e) =>
            {
                execute?.Invoke();
            };
            time.Start();
            timers[name] = time;
        }
    }
}